﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows.Controls;
using Caliburn.Micro;
using OI.Async;
using OI.DataModel;
using OI.Framework;
using OI.Views;

namespace OI.ViewModels
{
    [Export(typeof(DatasetDetailsDataViewModel))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class DatasetDetailsDataViewModel : DataGridScreenViewModelBase
    {
        #region DATA

        // the dataset we are detailing
        public DataGrid DetailsGrid;
        public OIDataset DatasetDetail 
        {
            get
            {
                return _DatasetDetail;
            }
            set
            {
                _DatasetDetail = value;
                 Coroutine.BeginExecute(LoadSampleData());
            }
        }
        private OIDataset _DatasetDetail;

        #endregion


        // on view loaded, dynamically setup datagrid
        protected override void OnViewLoaded(object view)
        {
            base.OnViewLoaded(view);
            DetailsGrid = ((DatasetDetailsDataView)view).Details;
             Coroutine.BeginExecute(LoadSampleData());
        }


        // coroutine for async download of dataset sample data
        public IEnumerator<IResult> LoadSampleData()
        {
            if (DatasetDetail != null &&
               !string.IsNullOrEmpty(DatasetDetail.TableName) &&
                DetailsGrid != null)
            {
                IoC.Get<IShell>().Busy(true, "loading sample data...");

                var dsq = new MDNDatasetAttributeQuery(DatasetDetail.TableName, null);
                yield return dsq;

                var res = dsq.Results;
                if (res != null && res.Count > 0)
                {
                    var qrt = res[0];

                    // build a StringTable from the results
                    var st = new StringTable(qrt.Fields);

                    // add rows
                    qrt.QueryResultRows.ForEach((row) => st.AddRow(row.Values));

                    // bind
                    st.BindStringTableToDataGrid(DetailsGrid);
                }

                IoC.Get<IShell>().Busy(false);
            }
        }
    }
}
